#include "util_popen.h"

int util_execute_shell(const char *cmd, char *buf, int len)
{
    int ret = 0, length = 0;
    FILE *fp;

    // 执行预先设定的命令，并读出该命令的标准输出
    // 这时执行shell命令的相关内容不会出现在标准输出上
    fp = popen(cmd, "r");
    if (NULL == fp)
    {
        printf("popen cmd:%s failure.\n", cmd);
        return -1;
    }

    if (buf != NULL)
    {
        memset(buf, 0x00, len);
        if ((length = fread(buf, 1, len - 1, fp)) < 0)
        {
            printf("Read from fp failure:%s\n", strerror(errno));
            return -1;
        }
    }
    // cmd执行成功返回值为0
    // cmd执行失败返回值为非0
    // 关闭文件指针
    ret = pclose(fp);
    ret = (length > 0) ? length : ret;
    return ret;
}

#if 0

int main(void)
{
    int ret;
    char buf[1024];
    char *cmd = "lspci | grep -i vga";
    // char *cmd = "ls test.c";
    ret = util_execute_shell(cmd, buf, sizeof(buf));
    printf("cmd %s ret : %d, result : %s\n", cmd, ret, buf);
}

#endif
